package cn.tanghom.app.system.controller;

import cn.tanghom.support.utils.Md5Util;
import cn.tanghom.support.utils.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;

/**
 * 登录登出
 *
 * @author tanghom
 */
@Controller
@RequestMapping
public class LoginController {

    /**
     * 登录入口
     * @param request
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(HttpServletRequest request) {
        request.removeAttribute("error");
        return "login";
    }

    /**
     * 登录
     * @param loginName  登录名
     * @param loginPwd 密码
     * @param request
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String doLogin(String loginName, String loginPwd, HttpServletRequest request) {
        try {
            if(StringUtils.isNullOrEmpty(loginName)|| StringUtils.isNullOrEmpty(loginPwd)){
                request.setAttribute("error","请输入用户名和密码");
                return "login";
            }
            Subject user = SecurityUtils.getSubject();
            String loginPwdMd5 = Md5Util.encrypt(loginPwd);
            UsernamePasswordToken token = new UsernamePasswordToken(loginName, loginPwdMd5);
            try {
                user.login(token);
            } catch (LockedAccountException lae) {
                token.clear();
                request.setAttribute("error", "用户已经被锁定不能登录，请与管理员联系！");
                return "login";
            } catch (IncorrectCredentialsException e) {
                token.clear();
                request.setAttribute("error", "登录失败,密码错误!");
                return "login";
            } catch (AuthenticationException e) {
                token.clear();
                request.setAttribute("error", "帐号或密码不正确！");
                return "login";
            }
        }catch (Exception e){
            request.setAttribute("error","程序异常");
            return "login";
        }
        request.removeAttribute("error");
        return "redirect:/";
    }
}
